package com.hk.web.controller.pc;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hk.Mgr.web.message.StatusCode;
import com.hk.Mgr.web.message.order.FundInfoReq;
import com.hk.Mgr.web.message.order.FundInfoRes;
import com.hk.base.BaseCtrl;
//import com.hk.Mgr.web.message.order.FundInfo_YimiDBHelper;
import com.hk.base.ResponseBase;
import com.hk.commons.HqlFilter;
import com.hk.commons.JsonUtils;
import com.hk.commons.StringHelper;
import com.hk.commons.entity.FundInfo_Yimi;
import com.hk.commons.entity.product.Company;
import com.hk.commons.entity.yingmi.FundNav;
import com.hk.commons.utils.yingmi.YingmiApiUtils;
import com.hk.commons.vo.FundInfoVoNav;
import com.hk.service.IFundInfo_Yimi;
import com.hk.service.IFundNav;
import com.hk.service.product.ICompany;

@Controller
@RequestMapping(value = BaseCtrl.PC + "/fundCtrl")
public class pcFundInfoCtrl {

	@Autowired
	private IFundInfo_Yimi fundInfoService;
	@Autowired
	public YingmiApiUtils utils;

	@Autowired
	public IFundNav fundNavService;

	@Autowired
	public ICompany companyService;

	@Resource
	private JdbcTemplate jdbcTemplate;

	private Logger logger = LoggerFactory.getLogger(pcFundInfoCtrl.class);

	@ResponseBody
	@RequestMapping(value = "/fundInfoList", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
	public ResponseBase<List<FundInfoVoNav>> fundInfoList(
			@RequestBody FundInfoReq req) {
		logger.info(
				"seacher fundType:{} , curPage:{} , pageSize:{}, orderByType:{}",
				req.getFundType(), req.getCurPage(), req.getPageSize(),
				req.getOrderByType());

		ResponseBase<List<FundInfoVoNav>> responseBase = new ResponseBase<List<FundInfoVoNav>>();

		try {
			String fundType = req.getFundType();
			String fundCode = req.getFundCode();
			StringBuffer buf = new StringBuffer();
			String hql = "Select new com.hk.commons.vo.FundInfoVoNav(fi.fundFullName,fn.navDate,fn.fundCode , fn.nav , fn.oneWeekReturn , fn.dayReturn , fn.unitYield , fn.yearlyRoe , fi.fundType)"
					+ " from FundInfo_Yimi fi , FundNav fn where fi.fundCode = fn.fundCode and fi.onSale = 1 ";
			
			if(StringHelper.isNotEmpty(fundType )){
				hql += " and fi.fundType = " + fundType;
			}
			
			if(StringHelper.isNotEmpty(fundCode )){
				hql += " and ( fi.fundCode like '%" + fundCode+ "%' or fi.fundName like '%" + fundCode+ "%'  )";
			}
			

			/**
			 * 排序规则: 1 nav asc 2 nav desc 3 dayReturn asc 4 dayReturn desc 5
			 * unitYield(货币型基金) asc 6 unitYield(货币型基金) desc 7 yearlyRoe(货币型基金) 8
			 * yearlyRoe(货币型基金)
			 */
			buf.append(hql);
			if (req.getOrderByType() != null) {
				switch (req.getOrderByType()) {
				case "1":
					buf.append(" order by  nav asc");
					break;
				case "2":
					buf.append(" order by nav desc ");
					break;
				case "3":
					buf.append(" order by dayReturn asc");
					break;
				case "4":
					buf.append(" order by dayReturn desc");
					break;
				case "5":
					buf.append(" order by unitYield asc");
					break;
				case "6":
					buf.append(" order by unitYield desc");
					break;
				case "7":
					buf.append(" order by yearlyRoe asc");
					break;
				case "8":
					buf.append(" order by yearlyRoe desc");
					break;
				default:
					buf.append("");
					break;

				}
			}

			int firstResult = (req.getCurPage() - 1) * req.getPageSize();
			int maxSize = req.getPageSize();
			
			logger.info("sql = " + String.valueOf(buf));
			
			@SuppressWarnings("unchecked")
			List<FundInfoVoNav> list = fundNavService.executeListHql(
					String.valueOf(buf), firstResult, maxSize);

			responseBase.setResult(list);

			@SuppressWarnings("unchecked")
			List<FundInfoVoNav> totalList = fundNavService.executeListHql(
					String.valueOf(buf), 1, 50000);

			responseBase.setSize(totalList.size());

			responseBase.setResultCode(StatusCode.SUCCESS.key());

			logger.info("请求结束，将要传出");
			
		} catch (Exception e) {
			logger.error("异常！：", e);
		}
		return responseBase;

	}

	@ResponseBody
	@RequestMapping(value = "/getFuu", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
	public String fundInfoList(@RequestParam String fundType) {
		StringBuffer buf = new StringBuffer();
		String hql = "Select new com.hk.commons.vo.FundInfoVoNav(fi.fundFullName,fn.navDate,fn.fundCode , fn.nav , fn.oneWeekReturn , fn.dayReturn , fn.unitYield , fn.yearlyRoe , fi.fundType)from FundInfo_Yimi fi , FundNav fn where fi.fundType = "
				+ fundType + " and fi.fundCode = fn.fundCode and fi.onSale = 1";
		/**
		 * 排序规则: 1 nav asc 2 nav desc 3 dayReturn asc 4 dayReturn desc 5
		 * unitYield(货币型基金) asc 6 unitYield(货币型基金) desc 7 yearlyRoe(货币型基金) 8
		 * yearlyRoe(货币型基金)
		 */
		buf.append(hql);

		@SuppressWarnings("unchecked")
		List<FundInfoVoNav> list = fundNavService.executeListHql(
				String.valueOf(buf), 0, 10);

		return JsonUtils.toJson(list);

	}

	/*
	 * @ResponseBody
	 * 
	 * @RequestMapping(value = "/fundInfo", method = RequestMethod.POST)
	 */
	public ResponseBase<String> getFundInfo(@RequestBody FundInfoReq req) {
		ResponseBase<String> resp = new ResponseBase<String>();

		logger.info("seacher fundType:{} , curPage:{} , pageSize:{}",
				req.getFundType(), req.getCurPage(), req.getPageSize());

		String fundInfoRes = getFundInfoById(req.getFundCode());
		if (fundInfoRes != null) {
			resp.setResultCode(StatusCode.SUCCESS.key());
			resp.setResult(fundInfoRes);
			resp.setSize(1);
		} else {
			resp.setMsg("获取基金信息失败");
			resp.setResultCode(StatusCode.EXCEPTION.key());
		}

		return resp;
	}

	/*
	 * @ResponseBody
	 * 
	 * @RequestMapping(value = "/updateAllFundInfo", method =
	 * RequestMethod.POST)
	 */

	/**
	 * 获取基金的基本信息
	 * 
	 * @param req
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/fundMessageList", method = RequestMethod.POST)
	public ResponseBase<List<FundInfoRes>> fundMessageList(
			@RequestBody FundInfoReq req) {
		ResponseBase<List<FundInfoRes>> resp = new ResponseBase<>();
		List<FundInfoRes> fundInfoResList = new ArrayList<>();
		HqlFilter hqlFilter = new HqlFilter();
		if (!req.getOnSale().equals("")) {
			int onSale = Integer.parseInt(req.getOnSale());
			hqlFilter.addEQFilter("onSale", onSale);// 过滤只在
		}
		hqlFilter.addEQFilter("fundType", req.getFundType());
		if (StringHelper.isNotEmpty(req.getFundFullName())) {
			hqlFilter.addLKFilter("fundFullName", req.getFundFullName());
		}

		if (StringHelper.isNotEmpty(req.getFundCode())) {
			hqlFilter.addEQFilter("fundCode", req.getFundCode());
		}
		hqlFilter.addSort("fundCode");
		hqlFilter.addOrder("desc");

		List<FundInfo_Yimi> list = fundInfoService.findByFilter(hqlFilter,
				req.getCurPage(), req.getPageSize());

		for (FundInfo_Yimi fundInfo : list) {
			FundInfoRes fundInfoRes = new FundInfoRes();
			// 设置基金信息
			fundInfoRes.setFundInfo(fundInfo);

			// 发行公司信息
			if (fundInfo.getCompanyId() != null) {
				Company company = companyService.findById(fundInfo
						.getCompanyId());
				fundInfoRes.setCompany(company);
			}

			fundInfoResList.add(fundInfoRes);
		}

		Long total = fundInfoService.countByFilter(hqlFilter);

		resp.setSize(total);
		resp.setResult(fundInfoResList);
		resp.setResultCode(200);
		return resp;

	}

	public void updateAllFundInfo() {
		HqlFilter hqlFilter = new HqlFilter();
		List<FundNav> list = fundNavService.findByFilter(hqlFilter, 0, 999999);
		for (FundNav fi : list) {
			String fundCode = fi.getFundCode();
			getFundInfoById(fundCode);
		}
	}

	private String getFundInfoById(String fundCode) {
		String resultStr = null;
		String url = "/product/getFundInfo";
		Map<String, String> params = new HashMap<>();
		params.put("fundCode", fundCode);
		resultStr = utils.get(url, params);

		/*
		 * FundInfo_YimiDBHelper fundInfo_YimiHelper = null; if (resultStr !=
		 * null) { fundInfo_YimiHelper = new FundInfo_YimiDBHelper();
		 * 
		 * try { fundInfo_YimiHelper = JsonUtils.toBean(resultStr,
		 * FundInfo_YimiDBHelper.class);
		 * 
		 * if (fundInfo_YimiHelper != null) { FundInfo_Yimi fundInfo_Yimi =
		 * getFromYimiHelper(fundInfo_YimiHelper); }
		 * 
		 * } catch (Exception e) { logger.error("类型转换错误， 无法查到基金信息 fundCode = " +
		 * fundCode); } // resultStr = JsonUtils.toJson(fundInfo_YimiHelper); }
		 */
		return resultStr;
	}
}
